package com.xuexiang.xuidemo.fragment.zhuanquanquan;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.aip.asrwakeup3.core.mini.AutoCheck;
import com.baidu.aip.asrwakeup3.core.recog.MyRecognizer;
import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.layout.XUILinearLayout;
import com.xuexiang.xui.widget.popupwindow.popup.XUISimplePopup;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.base.BaseFragment;
import com.xuexiang.xuidemo.entity.Decision;
import com.xuexiang.xuidemo.fragment.AboutFragment;
import com.xuexiang.xuidemo.utils.DrawableUtils;
import com.xuexiang.xuidemo.utils.XToastUtils;
import com.xuexiang.xuidemo.utils.ZhuanpanSPUtils;
import com.xuexiang.xuidemo.view.Microphone;
import com.xuexiang.xuidemo.view.Sector;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


@Page(name = "Decision",anim = CoreAnim.none)
public class ZhuanpanFragment extends BaseFragment implements Sector.AnimationEndListener, EventListener {


    private EventManager asr;
    private MyRecognizer rec;
    private Decision nowDecision;
    private ZhuanpanSPUtils zInstance;
    private List<Decision> decisions;
    private XUISimplePopup mPopup;

    @BindView(R.id.zhuanpan_text_title)
    TextView title;
    @BindView(R.id.zhuanpan_text_result)
    TextView result;
    @BindView(R.id.round_background)
    XUILinearLayout roundBackground;
    @BindView(R.id.button_background)
    XUILinearLayout buttonBackground;
    @BindView(R.id.sec)
    Sector sector;
    @BindView(R.id.zhuanpan_btn)
    ImageButton button;
    @BindView(R.id.microphone)
    Microphone microphone;

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setLeftImageResource(R.drawable.icon_action_about);
        titleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            @SingleClick
            public void onClick(View v) {
                mPopup.showDown(v);
            }
        });
        titleBar.addAction(new TitleBar.ImageAction(R.drawable.ic_action_menu) {
            @Override
            public void performAction(View view) {
                openNewPage(MyDecisionFragment.class);
            }
        });
        return titleBar;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_zhuanpan;
    }

    @Override
    public void onResume() {
        super.onResume();
        //Toast.makeText(getContext(), "重新启动", Toast.LENGTH_SHORT).show();
        nowDecision = zInstance.getDecisionById(zInstance.getChoice());
        setDecision(nowDecision);
        decisions = zInstance.getAllDecision();
    }

    public void setDecision(Decision decision) {
        if(decision == null) {
            zInstance.setChoice(0);
            decision = zInstance.getDecisionById(zInstance.getChoice());
        }
        sector.set(decision);
        title.setText(decision.getTitle());
        result.setText(decision.getResults().get(sector.queryPosition()));
    }

    @Override
    protected void initViews() {
        initPermission();
        initPopup();

        asr = EventManagerFactory.create(getContext(), "asr");
        asr.registerListener(this);

        if(rec == null)
        rec = new MyRecognizer(getContext(),this);

        roundBackground.setRadiusAndShadow(DensityUtils.dp2px(getContext(), 153),14,0.80f);
        buttonBackground.setRadiusAndShadow(DensityUtils.dp2px(getContext(), 50),14,0.80f);
        //sector = (Sector)findViewById(R.id.sec);
        //ImageButton button = (ImageButton)findViewById(R.id.zhuanpan_btn);

        zInstance = ZhuanpanSPUtils.getInstance();
        if(zInstance.getSum() == 0) {
            List<String> results = new ArrayList<>();
            results.add("饺子");results.add("大米饭");results.add("面条");
            List<Integer> weights = new ArrayList<>();
            weights.add(1);weights.add(1);weights.add(1);
            zInstance.addDecision(new Decision(3,"今天吃什么",results,weights));
        }

        if(zInstance.getLastColorStyle() != -1) {
            sector.setColors(ColorsProvider.colors[zInstance.getLastColorStyle()]);
        } else {
            sector.setColors(ColorsProvider.colors[0]);
        }

        sector.setAnimationEndListener(this);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            @SingleClick
            public void onClick(View view) {
                //start();
                sector.clearAnimation();
                sector.startRotate((int) (Math.random()*360));
            }
        });
        button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                start();
                microphone.start();
                return true;
            }
        });
        button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int action = motionEvent.getAction();

                if (action == MotionEvent.ACTION_DOWN) { // 按下
                    //start();
                } else if (action == MotionEvent.ACTION_UP) { // 松开
                    rec.stop();
                    microphone.stop();
                }
                return false;
            }

        });
    }

    private void initPopup() {

        mPopup = new XUISimplePopup(getContext(),ColorsProvider.colorsStyle)
                .create(DensityUtils.dp2px(getContext(), 70),DensityUtils.dp2px(getContext(), 170), (adapter, item, position) -> {
                    //XToastUtils.toast(item.getTitle().toString());
                    zInstance.setLastColorStyle(position);
                    sector.setColors(ColorsProvider.colors[position]);
                })
                .setHasDivider(true);
    }

    private void start() {
        //txtLog.setText("");
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        String event = null;
        event = SpeechConstant.ASR_START; // 替换成测试的event

        // 基于SDK集成2.1 设置识别参数
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        (new AutoCheck(getContext(), new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 100) {
                    AutoCheck autoCheck = (AutoCheck) msg.obj;
                    synchronized (autoCheck) {
                        String message = autoCheck.obtainErrorMessage(); // autoCheck.obtainAllMessage();
                        //txtLog.append(message + "\n");
                        ; // 可以用下面一行替代，在logcat中查看代码
                        // Log.w("AutoCheckMessage", message);
                    }
                }
            }
        }, false)).checkAsr(params);
        //String json = null; // 可以替换成自己的json
        //json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        //asr.send(event, json, null, 0, 0);
        rec.start(params);
    }

    @Override
    public void endAnimation() {
        result.setText(nowDecision.getResults().get(sector.queryPosition()));
    }

    @Override
    public void onEvent(String name, String params, byte[] data, int offset, int length) {

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            // 识别相关的结果都在这里
            if (params == null || params.isEmpty()) {
                return;
            }
            if (params.contains("\"nlu_result\"")) {
                // 一句话的语义解析结果
                if (length > 0 && data.length > 0) {
                    //logTxt += ", 语义解析结果：" + new String(data, offset, length);
                }
            } else if (params.contains("\"partial_result\"")) {
                // 一句话的临时识别结果
                //logTxt += ", 临时识别结果：" + params;
            }  else if (params.contains("\"final_result\""))  {
                // 一句话的最终识别结果
                //logTxt += ", 最终识别结果：" + params;
                try {
                    JSONObject json = new JSONObject(params);
                    String res = (String) json.get("best_result");
                    Toast.makeText(getContext(), res, Toast.LENGTH_SHORT).show();
                    for(int i=0;i<decisions.size();i++)
                    {
                        if((decisions.get(i).getTitle()+"。").equals(res) || (decisions.get(i).getTitle()+"？").equals(res))
                        {
                            zInstance.setChoice(decisions.get(i).getId());
                            nowDecision = decisions.get(i);
                            setDecision(nowDecision);
                            sector.startRotate((int) (Math.random()*360));
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }  else {
                // 一般这里不会运行
                //logTxt += " ;params :" + params;
                if (data != null) {
                    //logTxt += " ;data length=" + data.length;
                }
            }
        } else {
            // 识别开始，结束，音量，音频数据回调
            if (params != null && !params.isEmpty()){
                //logTxt += " ;params :" + params;
            }
            if (data != null) {
                //logTxt += " ;data length=" + data.length;
            }
        }
    }

    private void initPermission() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getContext(), perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.

            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(getActivity(), toApplyList.toArray(tmpList), 123);
        }

    }

}
